/*******************************************************************************
 * Copyright 2013 Mindaugas Idzelis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package incontrol.server;

import static com.google.common.base.Preconditions.checkNotNull;
import incontrol.core.protocol.IEvent;
import incontrol.plugin.protocol.Channel;

import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.LocalSession;
import org.cometd.bayeux.server.ServerMessage.Mutable;

public class EventManager {

	private BayeuxServer bayeuxServer;
	private LocalSession serverSession;

	public EventManager(BayeuxServer bayeuxServer, LocalSession serverSession) {
		this.bayeuxServer = bayeuxServer;
		this.serverSession = serverSession;
	}

	public void sendEvent(IEvent event) {
		String name = event.getClass().getAnnotation(Channel.class).name();
		checkNotNull(name, "Event must have @Channel annotation");

		Mutable newMessage = bayeuxServer.newMessage();
		newMessage.setData(event);
		newMessage.setChannel(name);
		bayeuxServer.createIfAbsent(name);
		bayeuxServer.getChannel(name).publish(serverSession, newMessage);
	}

}
